<template>
	<div class="app-container">
		<el-row :gutter="10">
			<el-form label-width="100px">
				<el-row :gutter="10">
					<el-col :span="1.5">
						<el-form-item label="名称/编码">
							<el-input size="mini" type="text" clearable placeholder="名称/编码" v-model="queryParams.searchValue" @keyup.enter.native="handleQuery"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="1.5">
						<el-form-item label="上架时间">
							<el-date-picker
								size="mini"
								v-model="dateRange"
								style="width: 240px"
								value-format="yyyy-MM-dd"
								type="daterange"
								range-separator="-"
								start-placeholder="开始日期"
								end-placeholder="结束日期"></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="1.5">
						<el-form-item label="是否上架">
							<el-select size="mini" clearable v-model="queryParams.status">
								<el-option :value="1" label="是"></el-option>
								<el-option :value="2" label="否"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="1.5">
						<el-form-item label="品牌">
							<el-select size="mini" clearable v-model="queryParams.brandId" @change="handleGetBrandPersonList" @clear="queryParams.brandPersonId = null">
								<el-option v-for="(item, index) in brandList" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="1.5">
						<el-form-item label="品牌系列">
							<el-select size="mini" clearable v-model="queryParams.brandPersonId">
								<el-option v-for="(item, index) in brandPersonList" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="1.5">
						<el-form-item label="分类">
							<el-select size="mini" clearable v-model="queryParams.goodsTypeId">
								<el-option v-for="(item, index) in goodsTypeList" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-row>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					size="mini"
					plain
					icon="el-icon-plus"
					@click="handleAdd"
					v-hasPermi="['system:role:add']">新增</el-button>
				<el-button
					type="danger"
					size="mini"
					plain
					icon="el-icon-delete"
					:disabled="ids.length <= 0"
					v-hasPermi="['system:user:admin']"
					@click="handleDelete">删除</el-button>
				<el-button
				  type="info"
				  plain
				  icon="el-icon-upload2"
				  size="mini"
				  @click="handleImport"
				  v-hasPermi="['system:user:admin']"
				>导入</el-button>
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleExport"
					v-hasPermi="['system:user:export']">导出</el-button>
				<!-- <el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleDownloadTemplate"
					v-hasPermi="['system:user:export']">下载模板</el-button> -->
				<el-button
					type="primary"
					plain
					icon="el-icon-upload2"
					size="mini"
					@click="hangleUp"
					:disabled="ids.length <= 0"
					v-hasPermi="['system:user:common']">上架</el-button>	
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="hangleDown"
					:disabled="ids.length <= 0"
					v-hasPermi="['system:user:common']">下架</el-button>	
				<el-button
					size="mini"
					type="primary" 
					icon="el-icon-search"
					@click="handleQuery">查询</el-button>
			</el-col>
		</el-row>	
			  
		<el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="图片" prop="name" width="100"  align="center">
				<template slot-scope="scope">
					<el-image
						v-if="scope.row.pictureUrl != null && scope.row.pictureUrl != ''"
						style="width: 80px; height: 80px"
						:src="baseUrl + scope.row.pictureUrl"
						:preview-src-list="[baseUrl + scope.row.pictureUrl]"
						fit="scale-down"></el-image>
						<el-image
							v-if="scope.row.pictureUrl == null || scope.row.pictureUrl == ''"
							style="width: 80px; height: 80px"
							:src="baseUrl + '/profile/static/icon/empty-picture.png'"
							fit="scale-down"></el-image>
				</template>
			</el-table-column>
			<el-table-column label="名称" prop="name" width="100"  align="center" />
			<el-table-column label="分类" prop="goodsType" width="80"  align="center">
				<template slot-scope="scope">
					{{ scope.row.goodsType != null?scope.row.goodsType.name:"" }}
				</template>
			</el-table-column>
			<el-table-column label="规格" prop="spec" width="140"  align="center" />
			<el-table-column label="状态" prop="status" width="80"  align="center">
				<template slot-scope="scope">
					<span :style="{color: scope.row.status == 2?'red':'green'}">{{ scope.row.status == 1?"已上架":"已下架" }}</span>
				</template>
			</el-table-column>	
			<el-table-column label="价格" prop="price" width="80"  align="center" />
			<el-table-column label="创建日期" prop="createTime" width="110"  align="center">
				<template slot-scope="scope">
					{{ parseTime(scope.row.createTime) }}
				</template>
			</el-table-column>
			<el-table-column label="更新日期" prop="updateTime" width="110"  align="center">
				<template slot-scope="scope">
					{{ parseTime(scope.row.updateTime) }}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template slot-scope="scope">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-edit"
						@click="handleUpdate(scope.row)">修改</el-button>
					<el-button type="text" size="mini" icon="el-icon-delete" v-hasPermi="['system:user:admin']" @click="handleDelete(scope.row)">删除</el-button>
					<el-button type="primary" size="mini" v-if="scope.row.status == 2" @click="hangleUp(scope.row)">上架</el-button>
					<el-button size="mini" v-if="scope.row.status == 1" @click="hangleDown(scope.row)">下架</el-button>
				</template>
			</el-table-column>
		</el-table>
		
		<pagination
		  v-show="total > 0"
		  :total="total"
		  :page.sync="queryParams.pageNum"
		  :limit.sync="queryParams.pageSize"
		  @pagination="handleQueryByPage"
		/>
		
		<!-- 用户导入对话框 -->
		<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
			<!-- <el-select style="width: 150px;margin-bottom: 20px;" clearable v-model="upload.goodsTypeId">
				<el-option v-for="(item, index) in goodsTypeList" :label="item.name" :value="item.id"></el-option>
			</el-select> -->
			<!-- :action="upload.url + '?goodsTypeId=' + upload.goodsTypeId" -->
			<el-upload
				ref="upload"
				:limit="1"
				accept=".xlsx, .xls"
				:headers="upload.headers"
				:action="upload.url"
				:disabled="upload.isUploading"
				:on-progress="handleFileUploadProgress"
				:on-success="handleFileSuccess"
				:auto-upload="false"
				drag>
				<el-progress v-if="upload.isUploading" :percentage="upload.progressPercent"></el-progress>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip text-center" slot="tip">
				  <div class="el-upload__tip" slot="tip">
					<el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
				  </div>
				  <span>仅允许导入xls、xlsx格式文件。</span>
				  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleDownloadTemplate">下载模板</el-link>
				</div>
			</el-upload>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFileForm">确 定</el-button>
				<el-button @click="upload.open = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { queryByPage, delByIds, update, insert } from "@/api/goods"
	import { getBarandList, getBrandPersonList } from "@/api/goods/brand"
	import { getInfo } from "@/api/login"
	import { getToken } from "@/utils/auth"
	import { getGoodsTypeList } from "@/api/goods/goodsType"
	import { Loading } from "element-ui"
	export default {
		name: "List",
		data() {
			return {
				loading: false,
				list: [],
				total: 0,
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					searchValue: "",
					isHasCustomized: null,
					goodsTypeId: null,
					brandId: null,
					brandPersonId: null,
					status: null,
				},
				dateRange: [],
				baseUrl: process.env.VUE_APP_BASE_API,
				ids: [],
				goodsTypeList: [],
				brandList: [],
				brandPersonList: [],
				// 用户导入参数
				upload: {
				  // 是否显示弹出层（用户导入）
				  open: false,
				  // 弹出层标题（用户导入）
				  title: "",
				  // 是否禁用上传
				  isUploading: false,
				  goodsTypeId: 1,
				  // 设置上传的请求头部
				  headers: { Authorization: "Bearer " + getToken() },
				  // 上传的地址
				  url: process.env.VUE_APP_BASE_API + "/goods/importData",
				  progressPercent: 0,
				},
				loadingInstance: null,
			}
		},
		mounted() {
			let that = this
			that.handleQueryByPage()
			that.handleGetGoodsTypeList()
			let state = that.$store.state
			if(state.user.name == "admin"){
				that.handleGetBarandList()
			}else{
				that.brandList = state.user.brands
				if(state.user.brands.length > 0){
					that.$nextTick(() =>{
						that.handleGetBrandPersonList()
					})
				}
			}
		},
		methods: {
			handleDownloadTemplate(){
				let that = this
				that.download("goods/downloadTemplate", {
				  // ...that.queryParams
				}, `goods_${new Date().getTime()}.xlsx`)
			},
			handleExport(){
				let that = this
				let queryParams = that.queryParams
				let param = {
					pageNum: queryParams.pageNum,
					pageSize: queryParams.pageSize,
				}
				if(queryParams.isHasCustomized != null && queryParams.isHasCustomized != ""){
					param.isHasCustomized = queryParams.isHasCustomized
				}
				if(queryParams.goodsTypeId != null && queryParams.goodsTypeId != ""){
					param.goodsTypeId = queryParams.goodsTypeId
				}
				if(queryParams.brandId != null && queryParams.brandId != ""){
					param.brandId = queryParams.brandId
				}
				if(queryParams.status != null && queryParams.status != ""){
					param.status = queryParams.status
				}
				if(queryParams.searchValue != null && queryParams.searchValue != ""){
					param.searchValue = queryParams.searchValue
				}
				
				that.download('goods/export', {
					...that.addDateRange(param, that.dateRange)
				}, `goods_${new Date().getTime()}.xlsx`)
			},
			/** 导入按钮操作 */
			handleImport() {
				let that = this
				that.upload.title = "用户导入";
				that.upload.open = true;
			},
			// 文件上传中处理
			handleFileUploadProgress(event, file, fileList) {
				let that = this
				that.progressPercent = parseInt(event.percent)
				// that.upload.progressPercent = Math.floor((event.loaded / event.total) * 100);
				that.loadingInstance = Loading.service({
				    fullscreen: true,
				    lock: true,
				    text: "导入中...",
				    spinner: 'el-icon-loading',
				    background: 'rgba(0, 0, 0, 0.7)'
				})
				that.upload.isUploading = true;
			},
			// 文件上传成功处理
			handleFileSuccess(response, file, fileList) {
				let that = this
				that.upload.open = false
				that.upload.isUploading = false
				that.$refs.upload.clearFiles()
				that.loadingInstance.close()
				that.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
				that.handleQueryByPage()
			},
			// 提交上传文件
			submitFileForm() {
				let that = this
				that.$refs.upload.submit();
			},
			handleGetBarandList(){
				let that = this
				getBarandList().then(res => {
					that.brandList = res.rows
				}).catch(function() {
				})
			},
			handleGetBrandPersonList(){
				let that = this
				let brandId = that.queryParams.brandId
				if(brandId == null || brandId == ""){
					return
				}
				that.queryParams.brandPersonId = null
				let param = {
					brandId: brandId
				}
				getBrandPersonList(param).then(res => {
					that.brandPersonList = res.rows
				}).catch(function() {
				})
			},
			handleGetGoodsTypeList(){
				let that = this
				getGoodsTypeList().then(res => {
					that.goodsTypeList = res.rows
				}).catch(function() {
				})
			},
			handleQuery() {
				let that = this
				that.pageNum = 1
				that.handleQueryByPage()
			},
			handleQueryByPage() {
				let that = this
				that.loading = true
				queryByPage(that.addDateRange(that.queryParams, that.dateRange)).then(res => {
					that.total = res.total
					let list = res.rows
					that.list = res.rows
					that.loading = false
				}).catch(function() {
				})
			},
			handleSelectionChange(selection) {
				let that = this
				that.ids = selection.map(item => item.id)
			},
			handleUpdate(res) {
				let that = this
				that.$router.push({
					path: "/goods/addGoods",
					query: {
						id: res.id
					}
				})
			},
			hangleUp(row) {
				let that = this
				let ids = row.id || that.ids
				that.$modal.confirm("您确定要上架您选择产品吗？").then(function() {
					groundingByIds(ids).then(res => {
						that.handleQueryByPage()
						that.$modal.msgSuccess("上架成功");
					}).catch(function() {
					})
				}).catch(function() {
				})
			},
			hangleDown(row) {
				let that = this
				let ids = row.id || that.ids
				that.$modal.confirm("您确定要下架您选择的产品吗？").then(function() {
					removeByIds(ids).then(res => {
						that.handleQueryByPage()
						that.$modal.msgSuccess("下架成功");
					}).catch(function() {
					})
				}).catch(function() {
				})
			},
			handleAdd() {
				let that = this
				that.$router.push({
					path: "/goods/addGoods",
					query: {
					}
				})
			},
			handleDelete(row) {
				let that = this
				const ids = row.id || that.ids;
				that.$modal.confirm("是否确认删除你选择的商品吗？").then(function() {
					delByIds(ids).then(res => {
						that.handleQueryByPage()
						that.$modal.msgSuccess("删除成功");
					}).catch(function() {
					});
				}).catch(() => {
				});
			},
		}
	}
</script>

<style>
</style>